//
//  MyMapNavigationController.m
//  iPhoneKML
//
//  Created by Benjamin Blundell on 12/11/2009.
//  Copyright 2009 Section9. All rights reserved.
//

#import "MyMapNavigationController.h"

@implementation MyMapNavigationController

@synthesize indicator;
@synthesize startFetch;
@synthesize masterData;
@synthesize	googleUsernameField;
@synthesize	googlePasswordField;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

#define DEBUG

- (IBAction)useOfflineMaps:(id)sender {

	if ([self loadCurrentMaps]){
		if (myMapViewController == nil) {
			myMapViewController = [[MyMapViewController alloc] initWithNibName:@"MyMapView" bundle:nil];
			myMapViewController.delegate = self;
		} 
		
		myMapViewController.tableMapData = [self.masterData allKeys];
		
		[self pushViewController:myMapViewController animated:YES];
		
	}else{
#ifdef DEBUG
		NSLog(@"Saved Data Error");
#endif
		
		UIAlertView *someError = [[UIAlertView alloc] initWithTitle: @"MyMap Error" message: @"No Saved Data could be loaded. Connect to Google First." delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
		
		[someError show];
		[someError release];
			
	}
	

}


- (IBAction)startGoogleFetch:(id)sender {
	
	const char *host_name = "google.com";

	
	if ([self checkConnection:host_name]){
	
		NSString *google_name = [googleUsernameField text];
		NSString *google_password = [googlePasswordField text];
		
		
		if (!grabber){
			grabber = [MyMapGrab alloc];
		}
		
		[grabber initWithUsername:google_name andPassword:google_password];
		[grabber setDelegate:self];
		
		[self saveUserDetails];
		
		startFetch.enabled = NO;
		
	//	[grabber fetchFeedOfMaps];

		[grabber fetchEntireFeed];
		
		if (self.masterData){
			[self.masterData removeAllObjects];
		}
		
		// Start the Progress Indicator
		
		[self drawIndicator];
	} else {
		
		//TODO: Create a proper Error Handler Class!
		
		UIAlertView *someError = [[UIAlertView alloc] initWithTitle: @"Connection Error" message: @"Cannot Connect to Google. Please check your Connection." delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
		
		[someError show];
		[someError release];
		[self.indicator removeFromSuperview];
		
	}

}


// Draw Background for our Indicator when it's on

-(void)drawIndicator{
	
	if (!self.indicator){
		CGRect mainBounds = [[UIScreen mainScreen] bounds];
		self.indicator = [[IndicatorView alloc] initWithFrame:mainBounds];
	}
	
	[self.view addSubview:self.indicator];
	
	
}

// Check to see if there is a net connection

- (BOOL) checkConnection:(const char*) host_name {
    BOOL _isDataSourceAvailable = NO;
    Boolean success;    
	
    //Creates a reachability reference to the specified 
    //network host or node name.
    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name);
	
    //Determines if the specified network target is reachable 
    //using the current network configuration.
    SCNetworkReachabilityFlags flags;
    success = SCNetworkReachabilityGetFlags(reachability, &flags);
    _isDataSourceAvailable = success && 
	(flags & kSCNetworkFlagsReachable) &&
	!(flags & kSCNetworkFlagsConnectionRequired);
	
    CFRelease(reachability);
	
    return _isDataSourceAvailable;
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	// This bit doesnt work with Jailbroken Apps so I have removed for now
	
//	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//	NSString *google_name = [defaults objectForKey:@"google_username"];
//	NSString *google_password = [defaults objectForKey:@"google_password"];
		
//	grabber = [[MyMapGrab alloc] initWithUsername:google_name andPassword:google_password];
//	[grabber setDelegate:self];

	[self loadUserDetails];
}


// Save the current data to a PLIST within the Documents Directory

- (void) saveCurrentMaps {

	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
													 NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	
	[self.masterData writeToFile:[NSString stringWithFormat:@"%@/mymapdata.plist", documentsDirectory] atomically:YES];

}


- (void) saveUserDetails {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
														 NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	
	NSMutableArray *userdetails = [[NSMutableArray alloc] init];
	
	NSString *google_name = [googleUsernameField text];
	NSString *google_password = [googlePasswordField text];
	
	[userdetails addObject:google_name];
	[userdetails addObject:google_password];
	
	[userdetails writeToFile:[NSString stringWithFormat:@"%@/mymapuser.plist", documentsDirectory] atomically:YES];

#ifdef DEBUG
	NSLog(@"Saved User Details: %@ %@",[userdetails objectAtIndex:0], [userdetails objectAtIndex:1]);
	
#endif
	
	
}

- (BOOL) loadUserDetails {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
														 NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/mymapuser.plist", documentsDirectory]]) {
		NSArray *userdetails = [[NSMutableArray alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/mymapuser.plist", documentsDirectory]];
		googleUsernameField.text = [userdetails objectAtIndex:0];
		googlePasswordField.text = [userdetails objectAtIndex:1];
		
		#ifdef DEBUG
		NSLog(@"Loaded User Details: %@ %@",[userdetails objectAtIndex:0], [userdetails objectAtIndex:1]);

		#endif
		
	}
	return FALSE;

}


- (BOOL) loadCurrentMaps {
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
														 NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/mymapdata.plist", documentsDirectory]]) {
	
#ifdef DEBUG
		NSLog(@"Loaded PLIST MyMaps File: %@",[NSString stringWithFormat:@"%@/mymapdata.plist", documentsDirectory]);
#endif
		
		self.masterData = [[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/mymapdata.plist", documentsDirectory]];
		
#ifdef DEBUG
		NSLog(@"Loaded Plist is: %@",self.masterData);
#endif
		
		return TRUE;
	
	}
	return FALSE;
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.startFetch = nil;
}


- (void)dealloc {
    [super dealloc];
	[myFeaturesViewController release];
	[myMapViewController release];
	[self.indicator release];
	[self.masterData release];
}

#pragma mark -
#pragma mark MyMapGrabDelegate Methods

- (void) myMapGrabDelegate:(MyMapGrab*)mm finishedMapFetch:(NSMutableDictionary*)mymaps {

	[self.indicator removeFromSuperview];
	
	// Inform the correct view
	
	if (myMapViewController == nil) {
		myMapViewController = [[MyMapViewController alloc] initWithNibName:@"MyMapView" bundle:nil];
		myMapViewController.delegate = self;
	} 
	
	myMapViewController.tableMapData = mymaps;
	
#ifdef DEBUG
	NSLog(@"MyMapView Controller Memory Location from Nav: %@",myMapViewController);
#endif
	[self pushViewController:myMapViewController animated:YES];
}

- (void) myMapGrabDelegate:(MyMapGrab*)mm finishedMapDetailsFetch:(NSMutableDictionary*)mydetails{
	
	[self.indicator removeFromSuperview];
	startFetch.enabled = YES;
	
	
	if (myFeaturesViewController == nil) {
		myFeaturesViewController = [[MyFeaturesViewController alloc] initWithNibName:@"DetailView" bundle:nil];
		myFeaturesViewController.delegate = self;
	}
		
	
	myFeaturesViewController.tableMapData = mydetails;

#ifdef DEBUG
	NSLog(@"MyDetailsView Controller Memory Location from Nav: %@",myFeaturesViewController);
#endif
	[self pushViewController:myFeaturesViewController animated:YES];
	
}


- (void) myMapGrabDelegate:(MyMapGrab*)mm didReceiveError:(NSError*)error {
/*	UIAlertView *someError = [[UIAlertView alloc] initWithTitle: @"MyMap Error" 
														message: [error localizedDescription]
													   delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
	
	[someError show];
	[someError release];
	*/
	// Need to add some bits here to deal with fetch errors depending on the error

	[self.indicator removeFromSuperview];
	
}


- (void) myMapGrabDelegate:(MyMapGrab*)mm fetchedAllData:(NSMutableDictionary*)alldata {
#ifdef DEBUG
	NSLog(@"Entire Data Structure: %@",alldata);
#endif
	self.masterData = alldata;
	
	[self.indicator removeFromSuperview];
	
	if ([alldata count] > 0){
		
		[self saveCurrentMaps];
		
		if (myMapViewController == nil) {
			myMapViewController = [[MyMapViewController alloc] initWithNibName:@"MyMapView" bundle:nil];
			myMapViewController.delegate = self;
		} 
		
		myMapViewController.tableMapData = [alldata allKeys];
		NSLog(@"MyMapView Controller Memory Location from Nav: %@",myMapViewController);
		[self pushViewController:myMapViewController animated:YES];
		
	}
	else{
		// Nothing downloaded it appears
		
		UIAlertView *someError = [[UIAlertView alloc] initWithTitle: @"MyMap Error" 
														   message: @"Could not download any maps"
														  delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
		
		[someError show];
		[someError release];

		// Tidy Up
		self.masterData = nil;
	}
	
}


#pragma mark -
#pragma mark - MyMapViewControllerDelegate Methods

- (void) myMapViewController:(MyMapViewController*)mmvc didSelectMap:(NSString*)mapname {
	
/*	[self.view addSubview:indicator];
	[indicator startAnimating];
	[grabber fetchFeedOfPlacesWithMap:index]; */
	
	// REPLACED: This method doesnt call a fetch but looks at the already loaded data
	// This is what happens when we grab the whole lot at once
	
	
	if (myFeaturesViewController == nil) {
		myFeaturesViewController = [[MyFeaturesViewController alloc] initWithNibName:@"DetailView" bundle:nil];
		myFeaturesViewController.delegate = self;
	} 
	
	myFeaturesViewController.tableMapData = [self.masterData valueForKey:mapname];
	
#ifdef DEBUG
	NSLog(@"MyDetailsView Controller Memory Location from Nav: %@",myFeaturesViewController);
#endif
	
	[self pushViewController:myFeaturesViewController animated:YES];
	
	
}

#pragma mark -
#pragma mark - MyFeaturesViewControllerDelegate Methods

- (void) myFeaturesViewController:(MyFeaturesViewController*)mmvc didSelectFeature:(NSString*)t withData:(NSString*) data {
	
	if (googleMapViewController == nil) {
		googleMapViewController = [[GoogleMapViewController alloc] initWithNibName:@"GoogleMapView" bundle:nil];
	} 

#ifdef DEBUG
	NSLog(@"GoogleMapViewController Memory Location from Nav: %@",googleMapViewController);
#endif
	[self pushViewController:googleMapViewController animated:YES];
		
	if (data){
		NSArray *chunks = [data componentsSeparatedByString: @","];
		
		if ([chunks count] == 2){
		
			[googleMapViewController setLatitude:[[chunks objectAtIndex:1] floatValue] andLongitude:[[chunks objectAtIndex:0] floatValue]
										andTitle: t];
		}
	}
}








@end
